package main

import (
	"encoding/json"
	"fmt"
	"io"
	"math/rand"
	"net"
	"net/http"
	"os"
	"strings"
	"time"
)

type UserInfo struct {
	Username string `json:"username"`
	Password string `json:"password"`
}

func NetTest() (bool, error) {

	// 实现一个自动ping某个网站的功能
	url := "http://www.baidu.com"

	// 创建一个请求
	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		fmt.Println("Error creating request:", err)
		return false, err
	}

	// 发送请求
	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		fmt.Println("Error sending request:", err)
		return false, err
	}

	if resp.StatusCode == 200 {
		fmt.Println("The website is up!")
		return true, nil
	} else {
		fmt.Println("The website is down!")
		return false, nil
	}
}

func LookTest(idx, count int) (bool, int) {

	minfunc := func(a, b int) int {
		if a > b {
			return b
		}
		return a
	}

	maxfunc := func(a, b int) int {
		if a > b {
			return a
		}
		return b
	}

	loopfunc := func(host string) bool {
		// 使用 net.LookupHost 进行 DNS 解析
		hosts, err := net.LookupHost(host)
		if err != nil {
			fmt.Println("DNS parsed:", err)
			return false
		}

		// 打印解析得到的主机名对应的所有 IP 地址
		for _, h := range hosts {
			fmt.Printf("host %s IP: %s\n", host, h)
		}

		// 使用 net.LookupCNAME 获取 CNAME 记录
		cname, err := net.LookupCNAME(host)
		if err != nil {
			fmt.Println("get CNAME record failed:", err)
			return false
		}
		fmt.Printf("host %s CNAME record: %s\n", host, cname)
		return true
	}

	hosts := []string{
		"example.com",
		"bilibili.com",
		"baidu.com",
		"buaa.edu.cn",
		"gitee.com",
		"www.bupt.edu.cn",
	}

	idx = minfunc(idx, len(hosts))
	idx = maxfunc(idx, 0)
	count = minfunc(count, len(hosts))
	count = maxfunc(count, 0)
	endidx := (idx + count) % len(hosts)

	ok := 0
	for j := 0; j < count; j++ {
		index := (idx + j) % len(hosts)
		if loopfunc(hosts[index]) {
			ok++
		}
	}
	var ratio float64 = 100.0 * float64(ok) / float64(count)
	return ratio >= 50.0, endidx
}

func LoginNet() {
	// 定义请求的URL
	url := "http://10.3.8.211/login"

	// 加载 config.json 文件
	file, err := os.Open("conf.json")
	if err != nil {
		fmt.Println("Error opening config file:", err)
		return
	}
	defer file.Close()

	conf, err := io.ReadAll(file)
	if err != nil {
		fmt.Println("Error reading config file:", err)
		return
	}

	var userInfo UserInfo
	err = json.Unmarshal(conf, &userInfo)
	if err != nil {
		fmt.Println("Error parsing config file:", err)
		return
	}

	// user := "2023110908"
	// passwd := "803251CYMasd#"
	fmt.Printf("user: %s, passwd: %s\n", userInfo.Username, userInfo.Password)

	user := userInfo.Username
	passwd := userInfo.Password

	// 定义请求的参数
	data := fmt.Sprintf("user=%s&pass=%s", user, passwd)

	// 创建一个请求
	req, err := http.NewRequest("POST", url, strings.NewReader(data))
	if err != nil {
		fmt.Println("Error creating request:", err)
		return
	}

	// 设置请求头，模拟表单提交
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")

	// 发送请求
	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		fmt.Println("Error sending request:", err)
		return
	}
	defer resp.Body.Close()

	// 读取响应内容
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		fmt.Println("Error reading response body:", err)
		return
	}

	// 打印响应内容
	fmt.Println("Response body:", string(body))
}

func MainSystemRunV2() {

	go func() {
		for {
			LoginNet()
			fmt.Println("loop login")
			time.Sleep(23 * time.Hour)
			time.Sleep(time.Duration(rand.Intn(30)) * time.Minute)
		}
	}()

	interval := 70
	nxtIdx := 0
	perCnt := 3
	for {
		interval = 70
		result := false
		result, nxtIdx = LookTest(nxtIdx, perCnt)
		if !result {
			LoginNet()
			interval = 1
			fmt.Printf("LoopTest failed, LoginNet()")
		} else {
			interval = 70
			fmt.Printf("LoopTest ok, per %v minute check", interval)
		}
		time.Sleep(time.Duration(interval) * time.Minute)
	}

}

func main() {
	// LoginNet()
	MainSystemRunV2()
}
